import { GenTableColumnEntity } from '../../entities/gen-table-cloumn.entity';
import * as Lodash from 'lodash';

export const indexVue = (options) => {
  const html = htmlTemplate(options);
  const script = indexScript(options);
  return `
    ${script}
    ${html}
    <style lang="scss" scoped></style>
  `;
};

// 获取表格自定义插槽内容
const getTableSlotHtmlStr = (columns: GenTableColumnEntity[]) => {
  const filterColumn = columns.filter((item) => {
    const condition1 = item.isList === '1' && ['imageUpload', 'fileUpload', 'editor'].includes(item.htmlType);
    const condition2 = item.isList === '1' && item.dictType;
    return condition1 || condition2;
  });
  let htmlStr = ``;
  filterColumn.forEach((item) => {
    let comStr = '';
    if (item.dictType) {
      if (item.htmlType === 'checkbox') {
        comStr = `<dict-tag :options="dictData.${item.dictType}" :value="row.${item.javaField}.split(','):[]"  />`;
      } else {
        comStr = `<dict-tag :options="dictData.${item.dictType}" :value="row.${item.javaField}"  />`;
      }
    }
    if (item.htmlType === 'imageUpload') {
      comStr = `<image-preview  :src="row.${item.javaField}"  />`;
    }
    if (item.htmlType === 'fileUpload') {
      comStr = `<el-link type="primary">点击查看文件</el-link>`;
    }
    if (item.htmlType === 'editor') {
      comStr = `
        <el-popover
          placement="bottom"
          :width="200"
          trigger="click"
        >
          <template #reference>
            <el-link type="primary">查看详情</el-link>
          </template>
          <div v-html="row.${item.javaField}"></div>
        </el-popover>
      `;
    }
    htmlStr += `
        <template #plus-cell-${item.javaField}="{ row }">
          ${comStr}
        </template>
    `;
  });
  return htmlStr;
};

// 获取操作按钮内容
const getActionBarHtmlStr = (moduleName, businessName) => {
  return `
<el-button type="primary" plain icon="Plus" @click="handleAdd"  v-hasPermi="['${moduleName}:${businessName}:add']">新增</el-button>
<el-button  type="success"  plain  icon="Edit"  :disabled="gSelection.length !== 1"  @click="handleUpdate(gSelection[0])"  v-hasPermi="['${moduleName}:${businessName}:edit']" >
  修改
</el-button>
<el-button type="danger" plain icon="Delete" :disabled="gSelection.length === 0" @click="handleDelete(gSelection)" v-hasPermi="['${moduleName}:${businessName}:remove']" >
  删除
</el-button>
<el-button type="warning" plain  icon="Download" @click="handleExport" v-hasPermi="['${moduleName}:${businessName}:export']">
  导出
</el-button>
<ClockTimer :task="gGetList" />
<SearchAreaControl v-model="gShowSearchForm" />
  `;
};
const indexButtonTemplate = (moduleName, businessName) => {
  return `
   <!-- 操作列 -->
    <template #plus-cell-action="scope">
      <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['${moduleName}:${businessName}:edit']">修改</el-button>
      <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['${moduleName}:${businessName}:remove']">删除</el-button>
    </template>
  `;
};
// 获取筛选表单自定义插槽内容
const getSearchSlotHtmlStr = (columns: GenTableColumnEntity[]) => {
  const filterColumn = columns.filter((item) => {
    return item.isQuery === '1' && item.htmlType === 'datetime';
  });
  if (filterColumn.length === 0) {
    return ``;
  }
  const item = filterColumn[0];
  return `
      <template #plus-field-${item.javaField}>
           <el-date-picker  start-placeholder="开始时间" end-placeholder="结束时间"  v-model="gSearchForm.timeRange" type="daterange"  />
      </template>
  `;
};

// 导出脚本模板
const handlerExport = (moduleName: string, businessName: string) => {
  return `
      // 导出逻辑
      const  handleExport = () =>{
         proxy.download(
          '${moduleName}/${businessName}/export',
          {...gSearchForm.value},
          \`${businessName}_\$\{new Date().getTime()\}.xlsx\`
         )
     }`;
};

const htmlTemplate = (options: any) => {
  const { columns, moduleName, businessName, functionName } = options;
  const buttonTem = indexButtonTemplate(moduleName, businessName);
  const actionBarHtmlStr = getActionBarHtmlStr(moduleName, businessName);
  const tableSlotHtmlStr = getTableSlotHtmlStr(columns);
  const slotHtmlStr = getSearchSlotHtmlStr(columns);
  let html = '';

  html += `
<template>
  <div class="app-container">
    <div class="app-container__section">
      <PlusSearch :columns="columns" v-bind="searchBinds" v-model="gSearchForm">
       ${slotHtmlStr}
      </PlusSearch>
    </div>
    <div class="app-container__section">
      <PlusTable v-bind="tableBinds"  :columns="columns">
        <template #title>
          <table-title />
        </template>
        <template #empty>
          <el-empty image-size="100" description="暂无数据"></el-empty>
        </template>
         ${tableSlotHtmlStr}
        <template #toolbar>
         ${actionBarHtmlStr}
        </template>
        ${buttonTem}
      </PlusTable>
    </div>

    <!-- 添加或修改${functionName}对话框 -->
    <addForm ref="addFormRef" @refreshList="gGetList" />

  </div>
</template>
`;

  return html;
};

const indexScript = (options: any) => {
  const { BusinessName, moduleName, businessName } = options;
  const exportScript = handlerExport(moduleName, businessName);
  let script = '';
  const nameStr = Lodash.upperFirst(BusinessName);

  script += `
    <script setup >
    import { useCommonConfig,useColumnsDict} from './hook.js'
    import { useDelHook, useListHook } from '@/hooks/crud/index.js'
    import { useListConfigHook } from '@/hooks/usePlusConfigHook.js'
    import AddForm from './addForm.vue'
    defineOptions({
      name: '${nameStr}'
    })
    const { proxy,apiFn,primaryKey,moduleName,beforeDelFn } = useCommonConfig()
    const { dictData, columns } = useColumnsDict()
    
    // ====================列表逻辑=========================
    const gSearchForm = ref({  })
    const { gGetList, gAllExposeOption, } = useListHook({
      listApiFn: apiFn.listApiFn,
      gSearchForm,
      beforeRequest: (reqData) => {
        return reqData
      },
      afterRequest: (resData) => {
        return resData
      }
    })
    // ====================属性绑定=========================
    const { gTableBinds, gSearchBinds, gSelection, gShowSearchForm } = useListConfigHook()
    const tableBinds = computed(() => gTableBinds({ ...gAllExposeOption,primaryKey }))
    const searchBinds = computed(() => gSearchBinds({ ...gAllExposeOption } ))
    // ==================删除逻辑===========================
    const { gDelete } = useDelHook({
      delApiFn: apiFn.delApiFn,
      moduleName,
      beforeDelFn: (reqData) => beforeDelFn(reqData),
      afterDelFn: (resData) =>gGetList(),
    })
    const handleDelete = (data)=>{
      gDelete(data)
    }
    // ===================新增、修改======================
    const addFormRef = ref(null)
    // 新增操作
    function handleAdd() {
      addFormRef.value.gOpen()
    }
    // 修改操作
    function handleUpdate(row) {
      addFormRef.value.gOpen(row)
    }
    
    ${exportScript}
    </script>
    `;

  return script;
};
